package com.sc.javaee.controller;

import com.sc.javaee.pojo.Result;
import com.sc.javaee.pojo.Users;
import com.sc.javaee.service.userService;
import com.sc.javaee.util.JwtUtils;
import com.sc.javaee.util.UpDowns;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
public class userController {
    @Autowired
    userService us;
    @RequestMapping("/login")
    public Result login(@RequestBody Users u){
        Users user = us.login(u);
        if (user!=null){
            user.setToken(JwtUtils.createToken(u.getPhone()));
            return new Result(1,"登录成功",user);
        }
        return new Result(0,"登录失败");
    }

    @RequestMapping("/reg")
    public Result reg(Users u, MultipartFile myHead){
        // 检查手机号是否已存在
//        if (us.isPhoneExists(u.getPhone())) {
//            return new Result(0, "该手机号已被注册");
//        }
        String filename = UpDowns.upload(myHead);
        u.setHeadPic("/api/upload/"+filename);
        int i=us.add(u);
        if (i>0) return new Result(1,"注册成功");
        return new Result(0,"注册失败");
    }

    @RequestMapping("/isPhoneExists")
    public boolean isPhoneExists(@RequestBody Map<String, String> params) {
        String phone = params.get("phone");
        return us.isPhoneExists(phone);
    }

    @RequestMapping("/delMy")
    public Result delMy(@RequestBody Map<String, Object> params){
        Integer userId = (Integer) params.get("userId");
        String password = (String) params.get("password");

        if (userId == null) {
            return new Result(0, "用户ID不能为空");
        }
        // 验证用户身份（可选：验证密码）
        Users currentUser = us.select(userId);
        if (currentUser == null) {
            return new Result(0, "用户不存在");
        }
        // 如果需要密码验证
        if (password != null && !password.isEmpty()) {
            if (!currentUser.getPassword().equals(password)) {
                return new Result(0, "密码错误");
            }
        }
        // 执行删除操作
        int i = us.delete(userId);
        if (i > 0) {
            return new Result(1, "账户注销成功");
        }
        return new Result(0, "账户注销失败");
    }

    @RequestMapping("/updateMy")
    public Result update(@RequestParam(value = "userId", required = true) Integer userId,
                         @RequestParam(value = "username", required = false) String username,
                         @RequestParam(value = "sex", required = false) String sex,
                         @RequestParam(value = "birthday", required = false) String birthday,
                         @RequestParam(value = "headPic", required = false) MultipartFile headPic,
                         @RequestParam(value = "password", required = false) String password){
        Users u = new Users();
        u.setUserId(userId);
        if (username != null) {
            u.setUsername(username);
        }
        if (sex != null) {
            u.setSex(sex);
        }
        if (password != null && !password.isEmpty()) {
            u.setPassword(password);
        }
        // 处理生日日期转换
        if (birthday != null && !birthday.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date birthDate = sdf.parse(birthday);
                u.setBirthday(birthDate);
            } catch (Exception e) {
                return new Result(0, "日期格式错误，请使用yyyy-MM-dd格式");
            }
        }
        // 处理头像上传
        if (headPic != null && !headPic.isEmpty()) {
            String filename = UpDowns.upload(headPic);
            u.setHeadPic("/api/upload/" + filename);
        }
        int i = us.update(u);
        if (i > 0) {
            // 返回更新后的用户信息
            Users updatedUser = us.select(userId);
            updatedUser.setToken(JwtUtils.createToken(updatedUser.getPhone()));
            return new Result(1, "修改成功", updatedUser);
        }
        return new Result(0, "修改失败");
    }

}
